package com.lej.wx

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.widget.Toast
import com.lej.wx.data.WXShareInfo
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlin.random.Random


/**
 *  author: cjq
 *  date  : 2022/4/13 0013
 *  desc  :
 */
const val WX_LOGIN = "WX_LOGIN"
fun Context.wxLogin() {
    getApi()?.let {
        it.sendReq(
            SendAuth.Req().apply {
                scope = "snsapi_userinfo"
                state = "${Random.nextInt(10000)}wechat_sdk_demo"
            }
        )
    }
}

fun Context.wxShareText(str: String, plantForm: Int = SendMessageToWX.Req.WXSceneSession) {
    getApi()?.let {
        val textObj = WXTextObject().apply { text = str }
        val msg = WXMediaMessage().apply {
            mediaObject = textObj
            description = str
        }
        it.sendReq(getReq(msg))
    }
}

fun Context.wxShareLink(
    webUrl: String,
    thumb64:ByteArray,
    webTitle: String = "标题",
    webDesc: String = "描述",
    plantForm: Int = SendMessageToWX.Req.WXSceneSession
) {
    getApi()?.let {
        val webpage = WXWebpageObject()
        webpage.webpageUrl = webUrl
        val bitmap = BitmapFactory.decodeByteArray(thumb64, 0, thumb64.size)
        val msg = WXMediaMessage(webpage).apply {
            title = webTitle
            description = webDesc
            setThumbImage(bitmap)
        }
        it.sendReq(getReq(msg))
        bitmap.recycle()
    }
}

/**
 * 打开小程序
 */
fun Context.jumpMiniProgram(path: String,userName: String){
    val req = WXLaunchMiniProgram.Req()
    req.userName = userName // 填小程序原始id

    req.path =
        path ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。

    req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW // 可选打开 开发版，体验版和正式版

    getApi()?.sendReq(req)
}

fun Context.wxShareImg(bitmap: Bitmap, plantForm: Int = SendMessageToWX.Req.WXSceneSession) {
    getApi()?.let {
        val thumbBmp = Bitmap.createScaledBitmap(bitmap, 50, 50, true)
        thumbBmp.recycle()
        val msg = WXMediaMessage().apply {
            mediaObject = WXImageObject(bitmap)
            setThumbImage(thumbBmp)
        }
        it.sendReq(getReq(msg))
        bitmap.recycle()
    }
}

fun Context.wxShareImg(base64Byte: ByteArray, plantForm: Int = SendMessageToWX.Req.WXSceneSession) {
    val bitmap = BitmapFactory.decodeByteArray(base64Byte, 0, base64Byte.size)
    wxShareImg(bitmap)
}

private fun Context.getApi(): IWXAPI? {
    if (!checkInstallWx()) return null
    val api = WXAPIFactory.createWXAPI(this, BuildConfig.WX_APP_ID, true)
    val success = api.registerApp(BuildConfig.WX_APP_ID)
    if (!success) {
        Toast.makeText(this, "微信客户端唤起失败", Toast.LENGTH_SHORT).show()
        return null
    }
    return api
}

private fun getReq(msg: WXMediaMessage) = SendMessageToWX.Req().apply {
    transaction = ""
    message = msg
    scene = SendMessageToWX.Req.WXSceneSession
}

fun Context.shareSmallApp(info: WXShareInfo) {
    val miniProgramObj = WXMiniProgramObject().apply {
        webpageUrl =
            if (info.webpageUrl.isNullOrEmpty()) info.path else info.webpageUrl // 兼容低版本的网页链接
        miniprogramType = info.miniprogramType // 正式版:0，测试版:1，体验版
        userName = info.userName // 小程序原始id
        path = info.path //小程序页面路径
    }
    val msg = WXMediaMessage(miniProgramObj).apply {
        this.title = info.title
        this.description = info.description // 小程序消息desc
        thumbData = info.urlData // 小程序消息封面图片，小于128k
    }
    getApi()?.sendReq(getReq(msg))
}

private fun Context.checkInstallWx(): Boolean {
    return if (!PlatformUtil.isWeChatAvailable(this)) {
        Toast.makeText(this, "微信客户端似乎没有安装", Toast.LENGTH_SHORT).show()
        false
    } else true
}